package com.example.f8399.testdemo.activity;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.f8399.testdemo.BR;
import com.example.f8399.testdemo.BaseActivity;
import com.example.f8399.testdemo.R;
import com.example.f8399.testdemo.adapter.BindingViewHolder;
import com.example.f8399.testdemo.databinding.ActivityRxLaughingBinding;
import com.example.f8399.testdemo.entity.Test1Entity;
import com.example.f8399.testdemo.utils.retrofit.AppApi;
import com.example.f8399.testdemo.utils.retrofit.ServiceGenerator;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.ResponseBody;

public class RxLaughingActivity extends BaseActivity {

    ActivityRxLaughingBinding mBinding;
    private MoviesAdaper adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_rx_laughing);

        initView();
    }

    private void initView() {

        LinearLayoutManager layout = new LinearLayoutManager(this);
        mBinding.recyclerView.setLayoutManager(layout);
        mBinding.recyclerView.addItemDecoration(new DividerItemDecoration(this, layout.getOrientation()));
        adapter = new MoviesAdaper(this);
        mBinding.recyclerView.setAdapter(adapter);

        mBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                /*refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                }, 2000);*/
                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                });

            }
        });

        mBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                });
            }
        });
//        getData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mBinding.refreshLayout.autoRefresh();

    }

    private void getData() {
        AppApi.LoginApi loginApi = ServiceGenerator.createService(AppApi.LoginApi.class);

        /*mCompositeDisposable.add(loginApi.login2()
                .subscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, Test1Entity>() {
                    @Override
                    public Test1Entity apply(ResponseBody body) throws Exception {
                        String string = body.string();
                        Test1Entity entity = JSON.parseObject(string, Test1Entity.class);
                        return entity;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (!disposable.isDisposed()) {
                            showProgress();
                        }
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                       dismisssProgress();
                    }
                })
                .subscribe(new Consumer<Test1Entity>() {
                    @Override
                    public void accept(Test1Entity data) throws Exception {
                        if (data != null) {
                            List<Test1Entity.SubjectsBean> subjects = data.getSubjects();
                            if (subjects.size() > 0) {
                                adapter.setList(subjects);
                            }
                        }
                    }
                }));*/

        //上面注释的和下面的这段功能是一样的
        loginApi.login2()
                .subscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, Test1Entity>() {
                    @Override
                    public Test1Entity apply(ResponseBody body) throws Exception {
                        String string = body.string();
                        Test1Entity entity = JSON.parseObject(string, Test1Entity.class);
                        return entity;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Test1Entity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (!d.isDisposed()) {
                            mCompositeDisposable.add(d);
//                            showProgress();
                        }
                    }

                    @Override
                    public void onNext(Test1Entity data) {
                        //这里不用做判空处理，因为map 段处理数据如果是空的话，走不到这里的
                        List<Test1Entity.SubjectsBean> subjects = data.getSubjects();
                        if (subjects.size() > 0) {
                            adapter.setList(subjects);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
//                        dismisssProgress();
                        mBinding.refreshLayout.finishRefresh();
                        mBinding.refreshLayout.finishLoadMore();
                        adapter.setList(new ArrayList<Test1Entity.SubjectsBean>());
                        ToastUtils.showShort("请求出错了");
                    }

                    @Override
                    public void onComplete() {
//                        dismisssProgress();
                        mBinding.refreshLayout.finishRefresh();
                        mBinding.refreshLayout.finishLoadMore();
                    }
                });

    }

    boolean isDouBan = true;

    public void changeDomain(View view) {
        if (isDouBan) {
            isDouBan = false;

            RetrofitUrlManager.getInstance().setGlobalDomain("http://www.baidu.com");
            mBinding.refreshLayout.autoRefresh();
        } else {
            isDouBan = true;
            RetrofitUrlManager.getInstance().setGlobalDomain(AppApi.BASE_URL);
            mBinding.refreshLayout.autoRefresh();
        }
    }

    public class MoviesAdaper extends RecyclerView.Adapter<BindingViewHolder> {
        private List<Test1Entity.SubjectsBean> list = new ArrayList<>();
        private Context context;
        private final int EmptyTpye = -1;

        public MoviesAdaper(Context context) {
            this.context = context;
        }

        @NonNull
        @Override
        public BindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (viewType == EmptyTpye) {
                ViewDataBinding inflate = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_empty, parent, false);
                return new BindingViewHolder(inflate);
            }else {
                ViewDataBinding inflate = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_movie, parent, false);
                return new BindingViewHolder(inflate);
            }
        }

        @Override
        public void onBindViewHolder(@NonNull BindingViewHolder holder, int position) {
            int itemViewType = getItemViewType(position);
            if (itemViewType==EmptyTpye) {
                return;
            }
            ViewDataBinding binding = holder.getBinding();
            final Test1Entity.SubjectsBean bean = list.get(position);
            binding.setVariable(BR.adaper, this);
            binding.setVariable(BR.data, bean);

            View root = binding.getRoot();
            ImageView iv_avatar = root.findViewById(R.id.iv_avatar);
            RequestOptions options = new RequestOptions().placeholder(R.mipmap.ic_launcher);
            Glide.with(context).load(bean.getImages().getLarge()).apply(options).into(iv_avatar);

        }

        @Override
        public int getItemCount() {

            int size = list.size();
            if (size==0) {
                return 1;
            }else {
                return size;
            }
        }

        @Override
        public int getItemViewType(int position) {
            if (list.size() == 0 && position == 0) {
                return EmptyTpye;
            }
            return super.getItemViewType(position);
        }

        public void setList(List<Test1Entity.SubjectsBean> list) {
            this.list = list;
            notifyDataSetChanged();
        }
    }

}
